package com.share.tools;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * author:caifan
 * date:2019/11/13
 */
public class ReflectionUtils {

    /**
     * 根据反射设置字段值 lombok插件如果使用了
     * @param obj
     * @param fieldName
     * @param value
     * @throws Exception
     */
    public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
        Class<?> aClass = obj.getClass();
        List<Field> allField = new ArrayList<>();
        while (!Objects.equals(aClass.getSimpleName(), Object.class.getSimpleName())) {
            allField.addAll(Arrays.asList(aClass.getDeclaredFields()));
            aClass = aClass.getSuperclass();
        }
        Field field = allField.stream().filter(f -> f.getName().equals(fieldName)).findFirst().get();
        field.setAccessible(true);
        field.set(obj, value);
    }
}
